

from flask import current_app,request
from flask_restful import Resource
from comment.models.user import User
from comment.utils.sms_send import send_sms
from comment.utils.limiter import limiter as lmt
from . import constans
from flask_limiter.util import get_remote_address
import random
from comment.utils.shopping_redis import redis_client
from flask_restful.reqparse import RequestParser
from comment.utils import parser
from comment.models import db


#我们定义的测试资源类
class Shopping_User(Resource):
    def get(self):
        current_app.logger.info('我的测试日志')
        #这里的代码可能会用到User模型类
        return {'hello','测试'}


class User_SMS(Resource):
    """
    发生验证码的短信，同一个手机号不能在一分钟内访问多次
    """
    error_message="To mang message"
    decorators=[
        #三个参数：参数1：限流的速率,参数2：key_fanc,参数3：如果超出限制之后的提示信息
        lmt.limit(constans.LIMIT_SMS_CODE_BY_MOBILE,key_func=lambda :request.args['phone'],error_message=error_message),
        lmt.limit(constans.LIMIT_SMS_CODE_BY_IP,key_func=get_remote_address,error_message=error_message)]
    def get(self):
        phone=request.args.get('phone').strip()
        code=random.randint(100000,999999)
        result=send_sms(phone,code)
        #result  往里面添加手机号码
        result['phone']=phone

        #短信验证码发送成功之后，还需要把验证码存放在redis数据库中，以便下次验证,验证码时效为5分钟
        redis_client.setex("shopping:code:{}".format(phone),constans.SMS_CODE_EXPIRES,code)  #参数1：key,参数2：时效,参数3：验证码
        return result


class AutoerizationCodeResource(Resource):
    """
        提交手机号和验证码来进行验证
    """
    def post(self):
        rp=RequestParser()
        rp.add_argument("phone",type=parser.mobile,required=True)
        rp.add_argument("code",type=parser.regex(r'^\d{6}$'),required=True)
        args=rp.parse_args()
        phone=args.phone
        code=args.code

        #从redis数据库中得到之前保存的验证码
        key = 'shopping:code:{}'.format(phone)
        try:
            real_code=redis_client.get(key)
        except ConnectionError as e:
            current_app.logger.error(e)
            return {"message":"redis_db_connect error."},400
        #开始校验
        if not real_code or real_code.decode()!=code:
            return {"message":"real_code error."},400
        return {"phone":phone,"msg":"code success."}

class RegisterUserResource(Resource):
    """
        填写账号信息，完成用户的注册
    """
    def post(self):
        rp = RequestParser()
        rp.add_argument("phone", type=parser.mobile, required=True)
        rp.add_argument("username", required=True)
        rp.add_argument("password", required=True)
        rp.add_argument("email",type=parser.email, required=True)
        args=rp.parse_args()
        username=args.username
        password=args.password
        phone=args.phone
        email=args.email

        #验证用户名是否唯一：先从mysql数据库中根据当前用户名查询
        u=User.query.filter(User.username==username).first()
        if u:  #用户名已经存在
            current_app.logger.error("{}:用户名已经存在，请换一个".format(username))
            return {"msg":"The username is exist."},400

        #把用户信息保存到数据库中
        u=User(username=username,pwd=password,email=email,status=0)
        db.session.add(u)
        db.session.commit()
        return {"msg":"ok"}


